const xss = require('xss')
const { exec } = require('../db/mysql')

const getList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `

    if (author) {
        sql += `and author='${author}'`
    }

    if (keyword) {
        sql += `and title like '%${keyword}%' `
    }

    sql += `order by createtime desc;`

    // 返回 promise
    return exec(sql)
}

const getDetail = (id) => {
    // 根据 id 来获取某条博客的具体内容
    const sql = `select * from blogs where id='${id}'`
    // 因为返回的数组，所以讲数组的括号去掉，变成对象的形式
    return exec(sql).then(rows => {
        return rows[0]
    })
}

const newBlog = (blogData = {}) => {
    // blogData 是一个博客对象，包含 title content author属性

    const title = xss(blogData.title)
    const content = xss(blogData.content) 
    const author = blogData.author
    const createtime = Date.now() 

    const sql = `
        insert into blogs (title, content, author, createtime)
        values ('${title}', '${content}', '${author}', ${createtime});
    `
    return exec(sql).then(insertData => {
        return {
            id: insertData.insertId
        }
    })
    // return {
    //     id: 3 // 表示新建博客，插入到数据表里面的 id
    // }
}

const updateBlog = (id, blogData = {}) => {
    // blogData 是一个博客对象，包含 title content 属性

    // 更新时只需要更新blogData的 title content 属性

    const title = xss(blogData.title)
    const content = xss(blogData.content)

    const sql = `
        update blogs set title='${title}',content='${content}' where id=${id}
    `
    return exec(sql).then(updateData => {
        if (updateData.affectedRows > 0) {
            return true
        }
        
        return false
    })
}

const deleteBlog = (id, author) => {
    // id 就是要删除博客的id
    
    const sql = `
        delete from blogs where id=${id} and author='${author}'
    `
    
    return exec(sql).then(deleteData => {
        if (deleteData.affectedRows > 0) {
            return true
        }
        
        return false
    })
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}